'use strict'
var mongoose = require('mongoose')
var WorkCard = mongoose.model('workCard')

exports.inquire = async (ctx, next) => {
  var offset = parseInt(ctx.query.offset) || 0
  var count = parseInt(ctx.query.limit) || 15
  var queryArray = await WorkCard.find()
      .skip(offset)
      .limit(count);
  var total = await WorkCard.estimatedDocumentCount()
  ctx.body = {
    success: true,
    objects: queryArray,
    meta: {
      total_count: total
    }
  }
}
exports.add = async (ctx, next) => {
  try {
    var body = ctx.request.body;
    var data = new WorkCard({
      title: body.title,
      projector: body.projector,
      style: body.style,
      status: body.status,
      remark: body.remark
    });
    data.save();
    ctx.body = {
      success: true,
      message: '添加成功'
    }
  } catch (error) {
    ctx.body = {
      success: false,
      message: '服务器错误'
    }
  }
}
exports.update = async (ctx, next) => {
  try {
    var body = ctx.request.body;
    var msg = await WorkCard.findByIdAndUpdate(body._id, {
      title: body.title,
      style: body.style,
      status: body.status,
      remark: body.remark
    })
    ctx.body = {
      success: true,
      message: '编辑成功'
    }
  } catch (error) {
    ctx.body = {
      success: false,
      message: '服务器错误'
    }
  }
}
exports.remove = async (ctx, next) => {
  try {
    var id = ctx.query && ctx.query.id
    if(id) {
      var msg = WorkCard.findOneAndRemove({_id: id}).exec();
      if(msg){
        ctx.body = {
          success: true,
          message: '删除成功'
        }
      }else{
        ctx.body = {
          success: false,
          message: '没有工牌！'
        }
      }
    }
  } catch (error) {
    console.log('删除失败');
  }
}